package com.vent.share.task;

import com.vent.common.core.redis.RedisCache;
import com.vent.common.utils.DateUtils;
import com.vent.common.utils.StringUtils;
import com.vent.mirai.constant.MiraiConstants;
import com.vent.share.service.ShareService;
import lombok.extern.slf4j.Slf4j;
import net.mamoe.mirai.Bot;
import net.mamoe.mirai.message.data.Face;
import net.mamoe.mirai.message.data.MessageChainBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Description: 股票定时任务相关
 *
 * @author ZiXiu
 * @date 2021/8/20 16:07
 */
@Slf4j
@Component
@Configuration
@EnableScheduling
public class ShareTask {
    @Autowired
    private ShareService shareService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 定时向redis中存入数据
     */
    @Scheduled(cron = "0 0 2 * * ?")
    private void taskGetShareData() {
        log.info("执行--定时获取新债数据");
        List<Map<String, String>> list = shareService.getShareDataFromSource();
        redisCache.deleteObject(MiraiConstants.NEW_SHARE_LIST);
        redisCache.setCacheList(MiraiConstants.NEW_SHARE_LIST, StringUtils.isEmpty(list) ? new ArrayList<>() : list);
    }

    /**
     * 定时发送提醒
     */
    @Scheduled(cron = "0 0 9 * * ?")
    private void taskSendRemind() {
        // 获取今日申购列表
        List<Map<String, String>> list = redisCache.getCacheList(MiraiConstants.NEW_SHARE_LIST);
        List<Map<String, String>> todayList = list.stream().filter(stringStringMap -> DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD).equals(stringStringMap.get("sub_date"))).collect(Collectors.toList());
        if (StringUtils.isNotEmpty(todayList)) {
            // 今日可申购新债
            MessageChainBuilder messagesBuilder = new MessageChainBuilder()
                    .append(new Face(Face.BIAN_PAO))
                    .append("今日可申购新债提醒：\n\n")
                    .append("日期：["+ DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD) +"]\n")
                    .append("可申购新债数量：["+ todayList.size() +"]\n")
                    .append(new Face(Face.BIAN_PAO))
                    .append("可申购新债如下：\n\n");
            todayList.forEach(todayMap -> {
                messagesBuilder.append(new Face(Face.HONG_BAO)).append(todayMap.get("bond_name") + "\n");
            });
            // 获取提醒用户集合
            Set<Long> userIds = redisCache.getCacheSet(MiraiConstants.REMIND_USER_LIST);
            userIds.forEach(userId -> {
                Bot.getInstance(2282552434L).getFriend(userId).sendMessage(messagesBuilder.build());
            });
        }
    }
}
